import { cloneDeep } from "lodash-es";
import { CustomQueryColumns, CustomQueryProps, CustomQueryValue } from "../types";
import { isArray, isEmpty } from "@/utils/is";

export function useInitialization(propsRef: ComputedRef<CustomQueryProps>) {
    const formValue = reactive<CustomQueryValue>({})
    const initValue = () => {
        let formColumns = cloneDeep<CustomQueryColumns[]>(unref(propsRef).formColumns)
        if (!isArray(formColumns) || isEmpty(formColumns)) []
        formColumns.forEach((item: CustomQueryColumns) => {
            formValue[item.key!] = item.value || null
        })

    }

    const setFormValue = (key: keyof typeof formValue,value: any) => {
        if(!value) return new Error('写入错误')
        formValue[key] = value
    }

    const resetFormValue = () => {
        initValue()
    }

    const getFormValue = computed(() => {
        return formValue
    })

    onMounted(() => {
        initValue()
    })

    return {
        getFormValue,
        setFormValue,
        resetFormValue
    }
}